package com.stu.controller;

import com.stu.pojo.User;
import com.stu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 * @author zy
 * @date 2025/4/12
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils; // 注入JwtUtils实例

    // 注册
    @PostMapping("/register")
    public ResponseEntity<User> register(@RequestBody User user) {
        User registeredUser = userService.register(user);
        registeredUser.setUserPassword(null); // 脱敏
        return ResponseEntity.ok(registeredUser);
    }

    // 登录
    @PostMapping("/login")
    public ResponseEntity<String> login(
            @RequestParam String username,
            @RequestParam String password) {
        String token = userService.login(username, password);
        return ResponseEntity.ok(token);
    }

    // 根据id获取用户信息
    @GetMapping("/{userId}")
    public ResponseEntity<User> getById(@PathVariable Integer userId) {
        return ResponseEntity.ok(userService.getById(userId));
    }

    // 更新用户信息
    @PutMapping("/{userId}")
    public ResponseEntity<User> update(
            @PathVariable Integer userId,
            @RequestBody User user,
            @RequestHeader("Authorization") String token) {

        Integer tokenUserId = jwtUtils.getUserIdFromToken(token);
        if (tokenUserId == null || !userId.equals(tokenUserId)) {
            return ResponseEntity.status(403).build();
        }

        user.setUserId(userId);
        return ResponseEntity.ok(userService.update(user));
    }

    // 修改密码
    @PutMapping("/{userId}/password")
    public ResponseEntity<Void> changePassword(
            @PathVariable Integer userId,
            @RequestParam String oldPassword,
            @RequestParam String newPassword,
            @RequestHeader("Authorization") String token) {

        Integer tokenUserId = jwtUtils.getUserIdFromToken(token);
        if (tokenUserId == null || !userId.equals(tokenUserId)) {
            return ResponseEntity.status(403).build();
        }

        userService.changePassword(userId, oldPassword, newPassword);
        return ResponseEntity.ok().build();
    }

    // 获取所有用户信息
    @GetMapping
    public ResponseEntity<List<User>> listAll() {
        return ResponseEntity.ok(userService.listAll());
    }

    // 更新用户状态
    @PutMapping("/{userId}/status")
    public ResponseEntity<Void> updateStatus(
            @PathVariable Integer userId,
            @RequestParam Integer status) {
        userService.updateStatus(userId, status);
        return ResponseEntity.ok().build();
    }
}
